package application.ratt.data_reader;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import application.ratt.city_model.City;
import application.ratt.city_model.Line;
import application.ratt.city_model.Station;

public class CityReader {
	
	private final String splitChar = ",";

public City readCity(InputStream fileName)
{
	BufferedReader br = null;
	String line = "";
    City c = new City();
	try
	{
		br = new BufferedReader(new InputStreamReader(fileName));
		while ((line = br.readLine()) != null)
		{
			String[] info = line.split(splitChar);
			info = formatWords(info);
			if (info[0].equals("LineID"))
			{
				Line transpLine = new Line();
				boolean lineInfo = true;
				boolean firstDirection = true;
				String[] lastReadInfo = null;
				while (lineInfo)
				{					
					line = br.readLine();
					info = line.split(splitChar);
					info = formatWords(info);
					if (info[0].equals(""))
					{
						if (lastReadInfo != null)
						{
							transpLine.setId(lastReadInfo[0]);
							transpLine.setName(lastReadInfo[1]);
							c.addLine(transpLine);
						}
						lineInfo = false;
					}
					else
					{
						if(!c.stationExists(info[2]))
						{
							Station s = new Station(info[2], info[3], info[4], info[5]);
							if (info[7].equals("") || info[8].equals(""))
							{
							   s.setCoordinates(0,0);
							}
							else
							{
							   s.setCoordinates(Double.parseDouble(info[7]), Double.parseDouble(info[8]));
							}
							if (!info[6].equals(""))
							{
								s.setJunction(info[6]);
							}
							c.addStation(s);
							c.addStationToJunctions(s);
						}
						
						if (lastReadInfo != null && lastReadInfo[5].equals(info[5]))
						{
							firstDirection = false;
						}
						
						if (firstDirection)
						{
							transpLine.addStationToFirstDirection(info[2]);
						}
						else
						{
							transpLine.addStationToSecondDirection(info[2]);
						}
						
						lastReadInfo = info;						
					}
				}		
			}
		}
	}
	catch (FileNotFoundException e)
	{
		e.printStackTrace();
	}
	catch (IOException e)
	{
		e.printStackTrace();
	}
	finally
	{
		if (br != null)
		{
			try
			{
				br.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
    return c;
}

private String[] formatWords(String[] in)
{
	for (int i=0; i<in.length; i++)
	{
		int length = in[i].length();
		if(length > 1)
		{
			if (in[i].charAt(0) == '"' && in[i].charAt(length-1) == '"')
			{
			   in[i] = in[i].substring(1, length-1);
			}
		}
	}
	return in;
}

}


